<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head th:replace="front-common :: commonCss(~{::title},~{},~{},~{::style})">
    <title>JAVA课程在线考试</title>
    <style type="text/css">
        .examInfo{
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            background-color: #ffffff;
            padding: 10px 0 10px 0;
            border: #f8f8f8 solid 10px;
        }
        .finish-flag-area{
            margin-top: 5px;
            margin-bottom: 5px;
            max-width: 90%;
            min-width: 90%;
            display: flex;
            align-items: center;
            flex-wrap: wrap;
        }
        .finish-flag-area span{
            max-width: 12%;
            min-width: 12%;
            flex-shrink: 1;
            margin: 5px 2% 5px 2%;
            padding: 0 2% 0 2%;
        }
        .questionArea{
            margin-top: 10px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            background-color: #ffffff;
            padding: 20px 30px 20px 30px;
        }
        .questionInfo{
            padding: 10px 20px 10px 20px;
            margin-bottom: 10px;
        }
        .questionInfo .content{
            font-size: 18px;
            font-weight: 1.6;
        }
        .questionInfo .answerArea{
            display: flex;
            flex-direction: column;
            justify-content: center;
            padding: 10px 5px 0 5px;
        }
        .layui-form-checkbox{
            margin-top: 5px;
            margin-bottom: 5px;
        }
    </style>
</head>
<body>
<div class="layui-layout layui-layout-admin">

    <div th:replace="front-common::exam_header()"></div>

    <div class="layui-layout-body" style="margin-top: 50px;background-color: #f8f8f8;">
        <div class="layui-container">
            <div class="layui-row layui-col-space30" style="margin-top: 30px;margin-bottom: 40px;">
                <div class="layui-col-md10 questionArea">
                    <fieldset th:if="${paper.radioCount} gt 0" class="layui-elem-field layui-field-title">
                        <legend>单选题</legend>
                    </fieldset>
                    <div id="radioArea">
                    </div>

                    <fieldset th:if="${paper.selectCount} gt 0" class="layui-elem-field layui-field-title">
                        <legend>多选题</legend>
                    </fieldset>
                    <div id="selectArea">
                    </div>

                    <fieldset th:if="${paper.judgeCount} gt 0" class="layui-elem-field layui-field-title">
                        <legend>判断题</legend>
                    </fieldset>
                    <div id="judgeArea">
                    </div>
                </div>
                <div class="layui-col-md2 examInfo">
                    <div style="align-self:stretch;">
                        <fieldset class="layui-elem-field layui-field-title">
                            <legend style="font-size: 14px;">剩余时间</legend>
                        </fieldset>
                    </div>
                    <div class="time" id="test"></div>
                    <div style="align-self:stretch  ;">
                        <fieldset class="layui-elem-field layui-field-title">
                            <legend style="font-size: 14px;">答题情况</legend>
                        </fieldset>
                    </div>
                    <div class="finish-flag-area" id="finishFlagArea">
                    </div>
                    <hr>
                    <div style="margin-top: 10px">
                        <button id="rememberBtn" type="button" class="layui-btn layui-btn-normal layui-btn-sm">保存</button>
                        <button id="submitBtn" type="button" class="layui-btn layui-btn-sm">提交</button>
                    </div>
                </div>
            </div>
        </div>

        <div th:replace="front-common::footer"></div>
    </div>

</div>

<script type="text/html" id="bar">
    <a class="layui-btn layui-btn-xs" lay-event="edit">查看试卷</a>
</script>
<script th:inline="javascript">

    var finishFlagPrefix = "finish_flag_";
    var questionPrefix = "question_";

    layui.use(['util','element','form'], function(){
        var util = layui.util;
        var element = layui.element;
        var form = layui.form;

        var endTime = new Date([[${exam.endTime}]]).getTime();
        var startTime = new Date([[${grade.attendTime}]]).getTime();
        var time = [[${exam.time}]]*60*1000;
        if((startTime+time) < endTime){
            endTime = startTime+time;
        }
        var serverTime = $.ajax({async:false}).getResponseHeader("Date");
        var nowTime = new Date(serverTime).getTime();
        util.countdown(endTime, nowTime, function(date, serverTime, timer){
            var hours = date[0]*24 + date[1];
            var str = hours+ ' 时 ' + date[2] + ' 分 ' + date[3] + ' 秒';
            $('#test').html(str);
            if(date[0]+date[1]+date[2]+date[3] <= 0){
                save();submit();
            }
        });

        var questionList = [[${questionList}]];
        var finishFlagAreaHtml = "";
        $.each(questionList,function (index,question) {
            var flag = finishFlagPrefix+question.id;
            finishFlagAreaHtml += "<span class='layui-badge' id='"+flag+"'>"+(index+1)+"</span>";
            var type = question.type;
            var answerHtml =
                "<div class='layui-panel questionInfo' flag='"+flag+"'>\n" +
                "    <div class='content'>\n" + question.content + "</div>\n" +
                "    <div class='answerArea layui-form'>";
            if(type===1){
                $.each(question.answerList,function (idx,answer) {
                    answerHtml += "<input class='answerClass' type='radio' name='"+questionPrefix+question.id+"' title='"+answer.content+"' value='"+answer.id+"'>";
                });
                answerHtml += "</div></div>";
                $("#radioArea").append(answerHtml);
            }else if(type===2){
                $.each(question.answerList,function (idx,answer) {
                    answerHtml += "<input class='answerClass' type='checkbox' name='"+questionPrefix+question.id+"' title='"+answer.content+"' value='"+answer.id+"' lay-skin='primary'>";
                });
                answerHtml += "</div></div>";
                $("#selectArea").append(answerHtml);
            }else if(type===3){
                answerHtml += "<input class='answerClass' type='radio' name='"+questionPrefix+question.id+"' title='正确' value='1'>";
                answerHtml += "<input class='answerClass' type='radio' name='"+questionPrefix+question.id+"' title='错误' value='0'>";
                answerHtml += "</div></div>";
                $("#judgeArea").append(answerHtml);
            }
            layui.form.render();
        })
        $("#finishFlagArea").html(finishFlagAreaHtml);
        $(document).on("click",".questionArea .layui-unselect",function(){
            var questionFlag = $(this).parent().parent().attr("flag");
            $("#"+questionFlag).attr("class","layui-badge layui-bg-green");
        });

        $("#rememberBtn").click(function () {save();});
        $("#submitBtn").click(function () {save();submit();});
        history();

        function save(){
            var list = [];
            $.each([[${questionList}]],function (index, question) {
                var select = $("*[name='"+questionPrefix+question.id+"']");
                var choice = select.map(function(){return $(this).is(':checked')}).get();
                var answers = select.map(function(){return $(this).val()}).get();
                var param = {"questionId": question.id,"answerList":answers,"choiceList":choice};
                list.push(param);
            });
            console.log(list);
            $.ajax({
                url : '/record/saveOrUpdate/'+[[${exam.id}]],
                type : 'post',
                async: false,
                contentType : 'application/json',
                dataType: 'json',
                data: JSON.stringify({
                    "msg":"",
                    "code":"",
                    "data": list
                }),
                success : function(n) {
                    if (n.result.status) {
                        layer.msg("保存成功!");
                    }else {
                        layer.msg("保存失败,"+n.result.msg);
                    }
                },
                error: function(n) {
                    layer.msg("保存失败,"+n.responseJSON.result.msg);
                }
            });
        }
        function submit(){
            $.ajax({
                url : '/exam/submit/'+[[${grade.id}]],
                type : 'post',
                async: false,
                contentType : 'application/json',
                dataType: 'json',
                success : function(n) {
                    if (n.result.status) {
                        layer.alert('提交成功！', {
                            time: 3*1000
                            ,success: function(layero, index){
                                var timeNum = this.time/1000, setText = function(start){
                                    layer.title((start ? timeNum : --timeNum) + ' 秒后关闭', index);
                                };
                                setText(!0);
                                this.timer = setInterval(setText, 1000);
                                if(timeNum <= 0) clearInterval(this.timer);
                            }
                            ,end: function(){
                                clearInterval(this.timer);
                                location.href='/index';
                            }
                        });
                    }else {
                        layer.msg("提交失败,"+n.result.msg);
                    }
                },
                error: function(n) {
                    layer.msg("提交失败,"+n.responseJSON.result.msg);
                }
            });
        }

        function history(){
            $.ajax({
                url : '/record/history/'+[[${exam.id}]],
                type : 'post',
                async: false,
                contentType : 'application/json',
                dataType: 'json',
                success : function(n) {
                    if (n.result.status) {
                        $.each(n.data,function (index, record) {
                            if(record.answeredId !== '' && record.answeredId !== null){
                                var answerIds = record.answeredId.split(",");
                                var questionFlag = finishFlagPrefix+record.questionId;
                                $("#"+questionFlag).attr("class","layui-badge layui-bg-green");
                                var select = $("*[name='"+questionPrefix+record.questionId+"']");
                                select.map(function(){
                                    var answerId = $(this).val();
                                    $(this).attr("checked",answerIds.includes(answerId));
                                });
                            }
                        });
                        layui.form.render();
                    }else {
                        layer.msg("获取做题记录失败,"+n.result.msg);
                    }
                },
                error: function(n) {
                    layer.msg("获取做题记录失败,"+n.responseJSON.result.msg);
                }
            });
        }
    });
</script>
</body>

</html>